from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem, QTextEdit, QHBoxLayout, QSizePolicy, \
    QHeaderView, QApplication

from style_manager import StyleManager
from base_pagination_view import BasePaginationView


class ChapterView(QWidget, BasePaginationView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.table = None
        self.current_page = 1
        self.total_pages = 1
        self.page_size = 5
        self.book_id = None  # 初始化book_id属性
        self.init_ui()

    def init_ui(self):
        """初始化UI组件"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)  # 设置间距为0

        # 表格设置
        self.table = QTableWidget()
        self.table.setColumnCount(6)
        self.table.setHorizontalHeaderLabels(["章节ID", "书本ID", "章节名称", "章节长度", "创建者", "操作"])

        # 先添加表格（使用stretch=1让表格占据剩余空间）
        layout.addWidget(self.table, stretch=1)

        # 再添加分页控制栏（现在会显示在表格下方）
        pagination_container = QWidget()
        pagination_layout = QHBoxLayout(pagination_container)
        pagination_layout.setContentsMargins(0, 10, 0, 10)  # 上下边距10px
        self.init_pagination_controls(pagination_layout)
        layout.addWidget(pagination_container)

        # 设置表格字体
        font = self.table.font()
        font.setPointSize(self.parent.default_font_size)
        self.table.setFont(font)

        # 设置表头字体
        header_font = self.table.horizontalHeader().font()
        header_font.setPointSize(self.parent.default_font_size)
        self.table.horizontalHeader().setFont(header_font)

        # 列宽调整函数
        def adjust_columns():
            if self.width() > 0:
                total_width = self.width()
                widths = [int(total_width * pct / 100) for pct in [15, 15, 30, 15, 15, 10]]
                for col, width in enumerate(widths):
                    self.table.horizontalHeader().resizeSection(col, width)
        def handle_resize(event):
            adjust_columns()
            if hasattr(self.__class__, 'resizeEvent'):
                super(self.__class__, self).resizeEvent(event)

        self.resizeEvent = handle_resize

        # 初始调整
        QTimer.singleShot(300, adjust_columns)

        layout.addWidget(self.table, stretch=1)

    def setup_table(self, chapter_data, column_widths=None):
        """设置章节表格
        :param column_widths: 列宽百分比列表，如[15, 15, 30, 15, 15, 10]
        """
        column_widths = column_widths or [15, 15, 30, 20, 10, 10]
        if chapter_data and 'list' in chapter_data and chapter_data['list']:
            self.table.setRowCount(len(chapter_data["list"]))

            # 确保表格已显示才能获取准确宽度
            self.table.show()

            # 统一使用百分比宽度设置
            header = self.table.horizontalHeader()
            total_width = self.table.viewport().width()  # 使用viewport宽度更准确
            for col, width_pct in enumerate(column_widths):
                header.resizeSection(col, int(total_width * width_pct / 100))

            # 填充数据
            for row_idx, chapter in enumerate(chapter_data["list"]):
                self.fill_row(row_idx, chapter)

    def fill_row(self, row_idx, chapter):
        """填充章节表格行"""
        for col_idx in range(5):
            item = QTableWidgetItem()
            if col_idx == 0:
                item.setText(str(chapter.get("id", "")))
            elif col_idx == 1:
                item.setText(str(chapter.get("book_id", "")))
            elif col_idx == 2:
                item.setText(chapter.get("chapter_name", ""))
            elif col_idx == 3:
                item.setText(str(chapter.get("chapter_len", "")))
            elif col_idx == 4:
                item.setText(chapter.get("creator", ""))
            item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row_idx, col_idx, item)

        # 编辑按钮
        button_widget = QWidget()
        button_widget.setProperty('class', 'theme-aware')  # 添加主题感知属性
        button_layout = QHBoxLayout(button_widget)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(7)  # 按钮的间距

        # 编辑按钮
        edit_button = self.parent.create_button("编辑",
                                              lambda checked, cid=chapter.get("id", ""): self.parent.show_chapter_detail(cid),
                                              is_edit=False)
        # 使用StyleManager获取按钮样式
        button_style = StyleManager.get_style("button", self.parent.current_theme)
        self.setStyleSheet(button_style)
        edit_button.setProperty('class', 'theme-aware')
        button_layout.addWidget(edit_button)
        self.table.setCellWidget(row_idx, 5, edit_button)

    def add_back_button(self, parent_layout, text, target_index):
        """添加返回按钮"""
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        back_button = self.parent.create_button(text, lambda: self.parent.switch_view(target_index))
        button_layout.addWidget(back_button)
        parent_layout.addLayout(button_layout)
    #
    # def add_log_box(self, parent_layout):
    #     """添加日志框"""
    #     log_box = QTextEdit()
    #     log_box.setReadOnly(True)
    #     log_box.setMaximumHeight(int(self.parent.height() * 0.1))
    #     parent_layout.addWidget(log_box)
    #     log_box.setPlainText(self.parent.log_box.toPlainText())

    def log_message(self, message, level):
        """记录日志消息"""
        if hasattr(self.parent, 'log_message') and callable(self.parent.log_message):
            self.parent.log_message(message, level)

    def adjust_table_columns(self, column_widths=None):
        """响应窗口大小变化，调整表格列宽
        :param column_widths: 列宽百分比列表，如[15, 15, 30, 15, 15, 10]
        """
        column_widths = column_widths or [15, 15, 30, 20, 10, 10]
        if hasattr(self, 'table') and self.table:
            header = self.table.horizontalHeader()
            if column_widths and len(column_widths) == 6:
                # 使用自定义百分比宽度
                total_width = self.table.width()
                for col, width_pct in enumerate(column_widths):
                    header.resizeSection(col, int(total_width * width_pct / 100))
            else:
                # 默认宽度策略
                header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
                header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
                header.setSectionResizeMode(2, QHeaderView.Stretch)
                header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
                header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
                header.setSectionResizeMode(5, QHeaderView.ResizeToContents)

    def fetch_data(self):
        """获取章节数据"""
        try:
            print(self.parent.book_id)
            # 调用父级的fetch_chapter_data方法获取数据
            data = self.parent.fetch_chapter_data(
                book_id=self.parent.book_id,
                page=self.current_page,
                page_size=self.page_size
            )

            if data and 'list' in data:
                # 设置表格数据
                self.setup_table(data)

                # 更新总页数
                total_items = data.get("total", len(data["list"]))
                self.total_pages = max(1, (total_items + self.page_size - 1) // self.page_size)

                # 更新分页控件状态
                self.update_pagination_controls()

                return data
            else:
                self.log_message("获取章节数据失败: 返回数据格式不正确", "error")
                return None

        except Exception as e:
            self.log_message(f"获取章节数据时出错: {str(e)}", "error")
            return None